<?php
/*
 * @Author: Terry
 * @Date: 2022-11-15 22:39:35
 * @LastEditors: Terry
 * @LastEditTime: 2024-12-05 16:35:34
 * @Description: file content
 * @FilePath: \auxface_certificate\app\common.php
 */
use think\facade\Db;
use think\facade\Request;

// Token相关返回代码/10000-11000
define('TOKEN_CREATE_FAIL', 10000); //token创建失败
define('TOKEN_TIMEOUT', 10001); //token过期
define('TOKEN_FAIL', 10002); //token错误
define('SECRET_KEY_FAIL', 10003); //token错误

//QRcode相关代码/11000 - 12000
define('QRCODE_TIMEOUT', 11001); //token错误

// 基本返回代码0/20000-25000
define('SUCCESS', 0); //api访问成功代码
define('FAIL', 20000); //通用错误返回代码
define('USER_UNREAL', 20001); //用户不存在
define('DATA_EMPTY', 20002); //缺少参数

// 权限相关返回代码30000-35000
define('GROUP_UNEXIST', 30000); //用户组不存在或已被禁用
define('AUTHORITY_UNEXIST', 30001); //用户组不存在或已被禁用
define('RULE_FAIL', 30002); //该用户没有权限

// 用户的增删改查相关的返回代码 35000-40000
define('USER_EXIST', 35000);

// 用户身份认证相关返回代码40001-45000
define('IDCARD_FAIL', 40001); //身份证照片错误
define('IDCARD_STATUS_FAIL', 40002); //身份证照片有问题
define('IDCARD_RISK_FAIL', 40003); //身份证只能用原件
define('AUTHENTICATED', 40004); //用户已申请
define('ID_EXIST', 40005); //身份证已存在
define('BUSINESS_NUM_EXIST', 40006); //企业已申请或已实名制
define('USER_HAS_IDENTITY', 40007); //用户已实名
define('USER_UN_CERTIFICATION', 40008); //用户未实名

//加入班组返回的错误代码 45001-46000
define('USER_IN_PROJECT', 45001); //您已加入该项目中的班组
define('USER_APPLED_PROJECT', 45002); //您已经提交申请请等待审批
define('USER_ROLE_ADMIN', 45003); //您已经提交申请请等待审批
define('USER_ROLE_GOVERNMENT', 45004); //您已经提交申请请等待审批
define('USER_ROLE_CORP', 45005); //您已经提交申请请等待审批

//更换用户头像 46001-47001
define('CHANG_AVATAR_FAIL', 46001); //您已经提交申请请等待审批
define('NOT_NEW_AVATAR', 46002); //您已经提交申请请等待审批
define('OLD_AVATAR_UNDEFINDE', 46003); //您已经提交申请请等待审批

define('SOCKET_CONNECT_SUCCESS', 50000); //连接成功

/**
 * @Description: 检查网络是否在线
 * @Author: Terry
 * @Date: 2023-10-20 16:46:27
 */
function checkNet()
{
    $url         = 'https://www.baidu.com';
    $headerArray = ["Content-Type:application/json;", "Accept:application/json"];
    $ch          = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 200);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    $output = (bool) curl_exec($ch);
    return $output;
}

/**
 * [result 返回值]
 * @param  [type] $code    [返回代码]
 * @param  string $data    [返回数据]
 * @param  [type] $message [返回信息]
 * @return [type]          [description]
 */
function result($code = 0, $data = '', $message = '')
{
    return json(['code' => $code, 'data' => $data, 'message' => $message]);
}

/**
 * [geturl get方法的curl]
 * @param  [string] $url [需要请求的地址]
 * @return [array]      [返回的数据]
 */
function getCurl($url)
{
    if (empty($url)) {
        return false;
    }

    $headerArray = array("Content-Type:application/json;", "Accept:application/json");
    $ch          = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    $output = curl_exec($ch);
    // dd($output);
    curl_close($ch);
    $output = json_decode($output, true);
    return $output;
}

/**
 * [geturl post方法的curl]
 * @param  [type] $url [需要请求的地址]
 * @param  [data] $param [请求的数据]
 * @return [type]      [array]
 */
function postCurl($url, $param, $decode = true)
{
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl  = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $data = curl_exec($curl);
    curl_close($curl);
    if ($decode) {
        return json_decode($data, true);
    }

    return $data;
}
/**
 * [getWechatToken 获取微信api的access_token]
 * 存时间6400s，储存位置public/wechat.txt
 * @return [type] [description]
 */
function getWechatToken($appid, $appSecret)
{
    $path = app()->getRootpath() . "/token/wechat";
    //已有token文件并token未过期无需访问微信获取token
    if (is_file($path . '/' . $appid . '.txt')) {
        $result = json_decode(file_get_contents($path . '/' . $appid . '.txt'));
        if (is_array($result) && $result['time'] > $_SERVER["REQUEST_TIME"]) {
            return $result['access_token'];
        }
    }
    //未获取token或token过期访问微信获取token
    $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appSecret}";
    $result = getCurl($url);
    if (isset($result['access_token'])) {
        if (!makeDir($path)) {
            return false;
        }

        $result['timeout'] = time() + 6400;
        file_put_contents($path . '/' . $appid . '.txt', json_encode($result));
        return $result['access_token'];
    }

    return false;
}

/**
 * [getBaiduToken 获取token]
 * 储存时间2590000s，储存位置public/baiduToken.txt
 * @return [string] [token值]
 */
function getBaiduToken($appKey, $secretKey)
{
    $path = app()->getRootpath() . "/token/baidu";
    //已有token文件并token未过期无需访问微信获取token
    if (is_file($path . '/' . $appKey . '.txt')) {
        $result = json_decode(file_get_contents($path . '/' . $appKey . '.txt'));
        if (is_array($result) && $result['time'] > $_SERVER["REQUEST_TIME"]) {
            return $result['access_token'];
        }
    }
    // api地址
    $url    = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$appKey}&client_secret={$secretKey}";
    $result = getCurl($url);

    if (isset($result['access_token'])) {
        if (!makeDir($path)) {
            return false;
        }

        $result['pass_time'] = time() + 2590000;
        $token               = $result['access_token'];
        $result              = json_encode($result);
        file_put_contents($path . '/' . $appKey . '.txt', $result);
        return $token;
    }
    return false;
}
/**
 * [getYS7Token 获取token]
 * 储存时间2590000s，储存位置public/baiduToken.txt
 * @return [string] [token值]
 */
function getYS7Token($appKey, $secretKey)
{
    $path = app()->getRootpath() . "/token/ys7";
    //已有token文件并token未过期无需访问微信获取token
    if (is_file($path . '/' . $appKey . '.txt')) {
        $result = json_decode(file_get_contents($path . '/' . $appKey . '.txt'), true);
        if (is_array($result) && $result['expireTime'] > time()) {
            return $result['accessToken'];
        }
    }
    $data = [
        'appKey'    => $appKey,
        'appSecret' => $secretKey,
    ];
    // api地址
    $url    = "https://open.ys7.com/api/lapp/token/get";
    $result = postCurl($url, $data, true);
    // 获取接口信息
    if ($result['code'] == 200) {
        if (!makeDir($path)) {
            return false;
        }

        $token                        = $result['data']['accessToken'];
        $result['data']['expireTime'] = substr($result['data']['expireTime'], 0, 10);
        $result                       = json_encode($result['data']);
        file_put_contents($path . '/' . $appKey . '.txt', $result);
        return $token;
    }
    return false;

}

/**
 * @Descripttion: 生成随机字符串
 * @name: getRandStr
 * @Author: Terry
 * @Date: 2020-09-05 16:42:53
 * @param param 几位数的字符串
 */
function getRandStr($param)
{
    $str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $key = "";
    for ($i = 0; $i < $param; $i++) {
        $key .= $str[mt_rand(0, 32)]; //生成php随机数
    }
    return $key;

}
/**
 * @Descripttion: 设置全库唯一码
 * @Author: Terry
 * @Date: 2021-10-04 19:12:15
 * @param {*}
 */
function createUuid()
{
    if (extension_loaded('uuid')) {
        $uuid = uuid_create(1);
        $uuid = str_replace('-', '', $uuid);
    } else {
        $uuid = md5(microtime(true) . mt_rand() . uniqid('', true));
    }

    return strtoupper($uuid);
}
/**
 * [base642image base64图片数据流转图片]
 * @param  [type] $base64 [ase64图片数据]
 * @param  [type] $path [图片地址]
 * @param  [type] $imagename [图片名字]
 * @return [type]         [description]
 */
function base642image($base64, $path, $imagename = '')
{
    if (!isBase64($base64)) {
        return $base64;
    }

    if (empty($imagename)) {
        $imagename = rand(1111, 9999) . "_" . time() . "_" . rand(1111, 9999) . '.jpg';
    }

    if (!makeDir($path)) {
        return false;
    }

    $imageSrc = $path . "/" . $imagename; //图片名字
    $r        = file_put_contents($imageSrc, base64_decode($base64)); //返回的是字节数
    // return $url.'/'.$imageSrc;
    return $imageSrc;
}
/**
 * [getClientIp 获取用户IP]
 * @return [type] [description]
 */
function getClientIp()
{
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } else if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $res = preg_match('/[\d\.]{7,15}/', $ip, $matches) ? $matches[0] : '';
    return $res;
}
/**
 * @Descripttion: 拼接数据
 * @name: dataMerge
 * @Author: Terry
 * @Date: 2020-10-12 21:47:20
 * @param $uuid 用户全库唯一id
 * @param $data 需要融合的数据
 * @param $insert true=》插入新数据 false=》更新数据
 */
function dataMerge($uuid = '', $data = [], $insert = true)
{
    if ($uuid != '') {
        $uuid = $uuid;
    } else {
        $uuid = $_SERVER['HTTP_UUID'] ?? '';
    }

    if (isset($data['editDate']) || isset($data['inDate'])) {
        return $data;
    }
    $user = $uuid;

    $time = date('Y-m-d H:i:s', time());
    if ($insert) {
        $mergeData = [
            'editUserName' => '',
            'editDate'     => '',
            'inDate'       => $time,
            'inUserName'   => $user,
        ];
    } else {
        $mergeData = [
            'editUserName' => $user,
            'editDate'     => date('Y-m-d H:i:s', time()),
        ];
    }
    return array_merge($data, $mergeData);
}

/**
 * @Descripttion: 拼接查询工具
 * @name: selectMerge
 * @Author: Terry
 * @Date: 2020-10-23 00:02:06
 * @param {*}
 */
function selectMerge($data = [])
{
    $mer = [
        'inDate',
        'inUserName',
        'editDate',
        'editUserName',
        'isDelete',
    ];
    return array_merge($mer, $data);
}

/**
 * [getUrl 获取url完整地址]
 * @return [type] [description]
 */
function getUrl()
{
    return Request::scheme() . '://' . $_SERVER['HTTP_HOST'];
}
/**
 * 判断字符串是否base64编码
 */
function isBase64($str)
{
    return $str == base64_encode(base64_decode($str)) ? true : false;
}
/**
 * [createQrCode 生成二维码]
 * @param  [type] $companyuuid [description]
 * @param  [type] $projectuuid [description]
 * @return [type]              [description]
 */
function createQrCode($path, $name, $file = 'image/qrcode')
{
    // 获取基本配置
    $config    = DB::name('config')->field('wx_appid,wx_appsecret')->find(1);
    $appid     = $config['wx_appid'];
    $appSecret = $config['wx_appsecret'];
    $token     = getWechatToken($appid, $appSecret);
    // $token = getWechatToken('wx9ea910a5391ab166','7e1ae9826bc8adbea30d81bd29cdffe3');
    $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token={$token}";
    makeDir($file);
    $data = [
        'path' => $path,
    ];

    $qrCode = postCurl($url, json_encode($data), false);
    $file   = $file . '/' . $name;
    if (file_put_contents($file, $qrCode)) {
        return $file;
    }

    return false;
}
/**
 * @Description: 生成文件夹
 * @Author: Terry
 * @Date: 2022-06-14 14:52:26
 */
function makeDir($dir)
{
    if (!is_dir($dir)) {
        if (!mkdir($dir, 0777, true)) {
            return false;
        }
        chmod($dir, 0777);
    }
    return true;
}

/**
 * @Descripttion: 移除空参数
 * @name:arrayExc
 * @Author: Terry
 * @Date: 2020-10-26 20:05:35
 * @param {*}
 */
function arrayExc($data)
{
    $data = array_filter($data, function ($val) {return ($val === '' || $val === null) ? false : true;});
    return $data;
}

/**
 * @Descripttion: 生成随机数字
 * @name: getRandStr
 * @Author: Terry
 * @Date: 2020-09-05 16:42:53
 * @param param 几位数的数字
 */
function getRandNum($param)
{
    $str = "0123456789";
    $key = "";

    for ($i = 0; $i < $param; $i++) {
        $key .= $str[mt_rand(0, 9)]; //生成php随机数
    }
    return $key;
}

/**
 * @Descripttion: 连接转为文件路径
 * @name: url2file
 * @Author: Terry
 * @Date: 2021-05-19 18:27:49
 * @param {*}
 */
function url2path($path)
{
    $exploded = explode('.com/', $path);
    $imgPath  = end($exploded);
    return $imgPath;
}

/**
 * @Description: 因为dic前缀的字典表简体中文均用type表示，但是中间件lang 为zhCnName 简体中文时需要进行修改
 * @Author: Terry
 * @Date: 2024-04-28 21:24:07
 * @param {*} $lang
 */

function lang2type($lang)
{
    if (strstr($lang, 'zhCnName')) {
        return 'type';
    }
    return str_replace(' as name', '', $lang);
}


/**
 * @Description: 获取用户个人信息
 * @Author: Terry
 * @Date: 2024-12-05 15:32:56
 * @param {*} $prjCode 项目唯一码
 * @param {*} $wxappUserUuid 用户唯一码
 * @param {*} $filed 需要获取的参数
 * @param {*} $status 状态默认是进场 可选：进场：entry ；离场：exit；待进场：wait；全部：all
 * @return{*} 
 */
function getPrjWorker(string $prjCode,string $wxappUserUuid,array $filed=[],string $status='entry'){

    $where = [
        ['projectCode','=',$prjCode],
        ['wxappUserUuid','=',$wxappUserUuid],
    ];
    $statusWhere = [];
    switch ($status) {
        case 'wait':
            $statusWhere = [['entryTime', '=', "0000-00-00 00:00:00"]];
            break;
        case 'entry':
            $statusWhere = [
                ['entryTime', '<>', "0000-00-00 00:00:00"],
                ['exitTime', '=', "0000-00-00 00:00:00"],
            ];
            break;
        case 'exitTime':
            $statusWhere = [['exitTime', '<>', "0000-00-00 00:00:00"]];
            break;
    }

    $where = array_merge($statusWhere,$where);

    $defaultFiled = !empty($filed) ? $filed : ['workerName', 'projectCode', 'corpCode'];

    $data = DB::table('certification_projectworker')
    ->where($where)
    ->field($defaultFiled)
    ->select()->toArray();

    return $data;
}